
const fs = require("fs")
const path = require("path")


function render(response, filePath, type = "") {
  // 处理HTTP响应的相关操作
  response.writeHead(200, { "Content-Type": `${type ? type : "text/html"}; charset=utf-8` })
  response.write(fs.readFileSync(path.join(__dirname, filePath), "utf-8"))
  response.end()
}


const route = {
  // 定义路由处理函数，用于处理对/index路径的请求
  "/index": (response) => {
    // 渲染首页
    render(response, "/static/index.html")
  },
  // 定义路由处理函数，用于处理对/login路径的请求
  "/login": (response) => {
    // 渲染登录页面
    render(response, "/static/login.html")
  },
  // 定义路由处理函数，用于处理对/reg路径的请求
  "/reg": (response) => {
    // 渲染注册页面
    render(response, "/static/reg.html")
  },
  // 定义路由处理函数，用于处理对根路径/的请求
  "/": (response) => {
    // 渲染默认页面（首页）
    render(response, "/static/index.html")

  },
  // 定义路由处理函数，用于处理404错误
  "/404": (request, response) => {

    if (renderFileStatic(request, response)) {
      // response.write("Not Found")
      // response.end()
      return
    }



    // 处理404错误，返回“Not Found”文本
    response.writeHead(404, { "Content-Type": "text/plain" })
    response.write("Not Found")
    response.end()
  }

}


function renderFileStatic(request, response) {

  const myUrl = new URL(request.url, "http://localhost:3000")
  const filePath = path.join(__dirname, "static", myUrl.pathname)


  if (fs.existsSync(filePath)) {


    render(response, "/static" + myUrl.pathname, `text/${myUrl.pathname.split(".")[1]}`)
    return true
  }
  return false

}



module.exports = route
